import type { Directive, DirectiveBinding } from 'vue'

let timer: ReturnType<typeof setTimeout> | null = null

const clearTimer = () => {
  timer && clearTimeout(timer)
  timer = null
}

const preventReclick: Directive = {
  mounted(el: HTMLButtonElement, binding: DirectiveBinding) {
    console.log(binding.value)

    el.addEventListener('click', () => {
      clearTimer()
      if (!el.disabled) {
        el.disabled = true
        timer = setTimeout(() => {
          el.disabled = false
        }, binding.value || 1000)
      }
    })
  },
  beforeUnmount() {
    clearTimer()
  }
}

export default preventReclick
